package com.store.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.adapter.TokenrecordListAdapter;
import com.store.app.database.Database;
import com.store.app.database.DatabaseMethod;
import com.store.app.http.Stores;
import com.store.app.http.Submit;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.MoneyUtil;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 礼券页面（余额）
 */
public class CouponBalanceActivity extends BaseActivity implements OnScrollListener{
	private Context context;
	private String error;
	private TextView token;
	private ListView listrecord;
	private JSONArray data=new JSONArray();
	private TokenrecordListAdapter recordlist;
	private LinearLayout skip, retreat,cache;
	private Database database;
	private Handler handler;
	private View moreView;
	private int lastItem,count;
	private TextView tvTitle;
	//充值
	private TextView submit;
	private GoToLogin goToLogin;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.tokenrecord);
		//透明状态栏
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		context = CouponBalanceActivity.this;
		database = new Database(context);
		goToLogin=new GoToLogin(this);
		ExitApplication.getInstance().addActivity(this);
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
				super.handleMessage(msg);
				switch (msg.what) {
					case 0:
						count = recordlist.getCount();
						cache.setVisibility(View.GONE);
						moreView.setVisibility(View.GONE);
						recordlist = new TokenrecordListAdapter(context,data);
						listrecord.setAdapter(recordlist);
						break;
					case 1:
						Toast.makeText(CouponBalanceActivity.this, error,
								Toast.LENGTH_SHORT).show();
						break;
					case 2:
						new token_records().start();
						break;
					case 3:
						//listrecord.removeFooterView(moreView);
						Toast.makeText(CouponBalanceActivity.this, "已经没有了哦",
								Toast.LENGTH_SHORT).show();
						break;
					case 4:
						Toast.makeText(CouponBalanceActivity.this, "请检查本地网络！",
								Toast.LENGTH_SHORT).show();
						break;
					case 5:
//						Toast.makeText(CouponBalanceActivity.this, "登录超时请重新登录",
//								Toast.LENGTH_SHORT).show();
						DatabaseMethod.delete(database);
						Intent intent = new Intent();
						intent.putExtra("reLogin","yes");
						intent.setClass(CouponBalanceActivity.this, MainActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
						startActivity(intent);
						break;
					default:
						break;
				}
			}
		};
		initView();
		moreView = getLayoutInflater().inflate(R.layout.load, null);
		listrecord = (ListView) findViewById(R.id.listrecord);
		recordlist = new TokenrecordListAdapter(context,data);
		//listrecord.addFooterView(moreView);
		listrecord.setAdapter(recordlist);
		listrecord.setOnScrollListener(this);
		listrecord.setOnItemClickListener(new MyItemListener());
		cache= (LinearLayout) findViewById(R.id.cache);
		token = (TextView) findViewById(R.id.token);
		submit= (TextView) findViewById(R.id.submit);

		token.setText(MoneyUtil.addComma(Stores.voucher_balance+""));
		new token_records().start();
	}
	private void initView(){
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvTitle.setText("礼券");
		findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	public void onScroll(AbsListView view, int firstVisibleItem,
						 int visibleItemCount, int totalItemCount) {
		lastItem = firstVisibleItem + visibleItemCount - 1; // 减1是因为上面加了个addFooterView

	}

	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// 下拉到空闲是，且最后一个item的数等于数据的总数时，进行更新
		if (lastItem == count
				&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
			// Log.i(TAG, "拉到最底部");
			moreView.setVisibility(view.VISIBLE);
			handler.sendEmptyMessage(2);
		}
	}

	private final class MyItemListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> parent, View view, int position,
								long id) {

		}
	}


	public class token_records extends Thread {

		public void run() {
			try {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
				String s_date=df.format(new Date());// new Date()为获取当前系统时间
				String[] d_date=s_date.split("-");
//				Thread.sleep(2000);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("app_token", MainActivity.app_token));
				JSONObject paramsone=new JSONObject();
				//paramsone.put("transaction_date",time_sign(tsLong));
				paramsone.put("member_id", MainActivity.member_id);
                paramsone.put("member_type_key", "stores");
				paramsone.put("tracked_date_start", d_date[0]+"-"+d_date[1]+"-"+"01");
				paramsone.put("tracked_date_end", s_date);
				Log.i("mylog", "aa" + paramsone.toString());
				params.add(new BasicNameValuePair("params", paramsone.toString()));
              params.add(new BasicNameValuePair("service", "finance.memberVoucherLogPageFind"));
//n  				params.add(new BasicNameValuePair("service", "finance.storeVoucherBill"));
				String sign=Submit.genPackageSign(params);
				params.add(new BasicNameValuePair("sign",sign));
				JSONObject obj = Submit.submit(params,Stores.http+"/openapi/finance");

				String result =  obj.getString("rsp_code");
				if(result.equals("succ")){
					JSONObject jsonObject=obj.getJSONObject("data");
					data = jsonObject.getJSONArray("list");
//n					data = obj.getJSONArray("data");
					handler.sendEmptyMessage(0);
				}else{
					if(goToLogin.setGoToLogin(obj)){

					}else {
						error = (String) obj.get("error_msg");
						handler.sendEmptyMessage(1);
					}
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				handler.sendEmptyMessage(4);
			}
		}
	}
	public String time_sign(long first_time) {
		Date date = new Date(first_time * 1000);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(date);
		return dateString;
	}

}